#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
int main(void)
{
    struct hostent* myHost;
    // char* name = "www.swu.edu.cn";
    // char * name = "www.baidu.com";
    char * name = "www.sina.com.cn";
    myHost = gethostbyname(name);
    if (myHost == NULL)
    {
        printf("get host failed.");
    }
    printf("name: %s\n", myHost->h_name);
    // 别名
    for (int i = 0; myHost->h_aliases[i]; ++i)
    {
        printf("aliase: %s\n", myHost->h_aliases[i]);
    }
    printf("Address type: %s\n", (myHost->h_addrtype==AF_INET) ? "AF_INET": "AF_INET6");
    // 先把ip地址强转为in_addr*, 然后解引用传入ntoa
    for (int i = 0; myHost->h_addr_list[i]; ++i)
    {
        printf("ip: %s\n", inet_ntoa(*(struct in_addr*)myHost->h_addr_list[i]));
    }

    struct in_addr myIp;
    // char* ipAddr = "202.202.96.35";
    // inet_aton(ipAddr, &myIp);
    myIp.s_addr = ((struct in_addr*)myHost->h_addr_list[0])->s_addr;
    myHost = gethostbyaddr(&myIp, sizeof(myIp), AF_INET);
    if (myHost == NULL)
    {
        printf("get host failed.");
        return -1;
    }
    printf("name: %s\n", myHost->h_name);
    // 别名
    for (int i = 0; myHost->h_aliases[i]; ++i)
    {
        printf("aliase: %s\n", myHost->h_aliases[i]);
    }
    printf("Address type: %s\n", (myHost->h_addrtype==AF_INET) ? "AF_INET": "AF_INET6");
    // 先把ip地址强转为in_addr*, 然后解引用传入ntoa
    for (int i = 0; myHost->h_addr_list[i]; ++i)
    {
        printf("ip: %s\n", inet_ntoa(*(struct in_addr*)myHost->h_addr_list[i]));
    }
    

    return 0;
}